<?php
/**
* RSA 签名，验签
* RSA 加密 解密
*/
class Rsa
{
	private $public;
	private $private;
	public $_path = array(
			'public_key_path' => 'cer/test.pub',
			'private_key_path' => 'cer/test.pri',
		);
	
	/**
	 * 初使化参数
	 * @param [type] $data [description]
	 */
	function __construct($data)
	{
		$this->public = file_get_contents(CWF_PATH.'data/'.$this->_path['public_key_path']);
		$this->private = file_get_contents(CWF_PATH.'data/'.$this->_path['private_key_path']);
		$this->data = $data;
	}

	/**
	 * 生成私钥，公钥
	 * @return [type] [description]
	 */
	public function createKey()
	{
		$conf = array(
			"digest_alg" => "sha512",
			"private_key_bits" => 4096,
			"private_key_type" => OPENSSL_KEYTYPE_RSA,
		);
		$res = openssl_pkey_new($conf);
		openssl_pkey_export($res,$pri);
		$d= openssl_pkey_get_details($res);
		$pub = $d['key'];
		$arr = array(
		    'pri' => $pri,
		    'pub' => $pub,
		);
		return $arr;
	}
	
	/**
	 * 生成待签名字符串
	 * 按字典排序，去除空值，拼字符串
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 * echo urldecode(http_build_query($data));
	 */
	public function trim_d()
	{
		ksort($this->data);
		$str = '';
		foreach ($this->data as $k => $v) {
			if (!empty($v)) {
				$str .= $k.'='.$v.'&';
			}	
		}
		return substr($str, 0, -1);
	}

	/**
	 * RSA签名
	 * @param  [String] $data             [待签名数据]
	 * @param  [String] $private_key_path [私钥文件路径]
	 * @return [String]                   [签名结果]
	 */
	public function rsaSign($data)
	{
		$res = openssl_pkey_get_private($this->private);
		openssl_sign($data, $sign, $res);
		openssl_free_key($res);
		//base64编码
		$sign = base64_encode($sign);
		return $sign;
	}

	/**
	 * RSA公钥验签
	 * @param $data 待签名数据
	 * @param $sign 传过来的签名值
	 * return 验证结果
	 */
	public function rsaVerify($data, $sign)
	{
		$res = openssl_pkey_get_public($this->public);
		$result = (bool)openssl_verify($data, base64_decode($sign), $res);
		openssl_free_key($res);
		return $result;
	}

	/**
	 * RSA 公钥加密
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function rsaEncrypt($data) {  
		$res = openssl_pkey_get_public($this->public);
		//待加密数据不能大于245字符
		if (openssl_public_encrypt($data, $encrypt, $res)) {
			openssl_free_key($res);
			$encrypt = base64_encode($encrypt);
		}else{
            return 'Unable to encrypt data. Perhaps it is bigger than the key size >245?';
        }
		return $encrypt;

    }

	/**
	 * RSA 私钥解密
	 * @param $content 需要解密的内容，密文
	 * @param $private_key_path 商户私钥文件路径
	 * return 解密后内容，明文
	 */
	public function rsaDecrypt($data)
	{
		$res = openssl_pkey_get_private($this->private);
		//用base64将内容还原成二进制
		$data = base64_decode($data);
		//把需要解密的内容，按128位拆开解密
		$result  = '';
		for($i = 0; $i < strlen($data)/256; $i++  ) {
			$data = substr($data, $i * 256, 256);
			openssl_private_decrypt($data, $decrypt, $res);
			$result .= $decrypt;
		}
		openssl_free_key($res);
		return $result;

	}


}